<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');
session_start();

$action = $_REQUEST['FORM_SUBMIT'];

$cart	= new shoppingCart();

switch($action){
	case "addtocart":
		$cart->addToCart();
		break;
	case "checkout":
		$cart->addToCart("shoppingcart.html");
		break;
	case "updatecart":
		$cart->updateCart();
		break;
	case "removefromcart":
		$cart->removeFromCart();
		break;
	case "removetobackpocket":
		$cart->removeToBackpocket();
		break;
}


class shoppingCart
{
	
	public function addToCart($url='')
	{
		$id			= $_POST['id'];
		$skuid		= $_POST['skuid'];
		$name		= $_POST['prodcut_name'];
		$gwPrice	= ($_POST['gwPrice']) ? number_format(floatval($_POST['gwPrice']), 2, '.', '') : '0';
		//$price		= (intval($_POST['gift_wrapping'])) ? number_format(floatval($_POST['price'] + $gwPrice), 2, '.', '') : number_format(floatval($_POST['price']), 2, '.', '');
		$price		= number_format(floatval($_POST['price']), 2, '.', '');
		$colour		= $_POST['colour'];
		$size		= $_POST['size'];	
		$quantity	= ($_POST['quantity'] != 'undefined') ? $_POST['quantity'] : '';
		$colour_ids	= $_POST['colour_ids'];
		$size_ids	= $_POST['size_ids'];
		$gift_wrapping = intval($_POST['gift_wrapping']);
		
		if (intval($_POST['quantity']) > 0 && $skuid && $name && $price && $colour && $size && $quantity && $colour_ids && $size_ids)
		{
			$stock = 0;
			// Get the stock information of this special product.
			$strSQL = "SELECT `tl_catalog_attribute`.*, catalog_colour.title  
						FROM `tl_catalog_attribute` 
						LEFT JOIN `catalog_colour` ON `catalog_colour`.id=`tl_catalog_attribute`.id_color
						WHERE `tl_catalog_attribute`.`id_catalog`=" . $id . " AND `catalog_colour`.`title`='" . $colour . "'  AND `tl_catalog_attribute`.`id_size`=" . $size;
			$this->setDB();
			$result = @mysql_query($strSQL);
			if ($row=@mysql_fetch_assoc($result))
			{
				$stock = intval($row['catalog_stock']);
			}
			
			if(!$stock)
			{
				// None stock.
				$is_addItems = false;
			}
			else 
			{		
				$sessionID	= $id."_".$size."_".trim(strtolower($colour));
				$quantity_total = 0;
				
				if (isset($_SESSION['cart'][$sessionID])){
					$quantity_total = $quantity + $_SESSION['cart'][$sessionID]['quantity'];
				}
				else
					$quantity_total = $quantity;
				
				if ($stock < intval($quantity_total))
				{
					$is_addItems = false;
					$quantity = 0;
				}		
				else 
				{	
					$is_addItems = true;
					
					if(isset($_SESSION['cart'][$sessionID])){
						/*$_SESSION['cart'][$sessionID]['gift_wrapping'] = ($gift_wrapping) ? $gift_wrapping : 0;
						$_SESSION['cart'][$sessionID]['price'] = $price;
						$_SESSION['cart'][$sessionID]['quantity'] += $quantity;*/
						$is_addItems = false;
						$quantity = 0;
					}else{
						$_SESSION['cart'][$sessionID] = array(
							"id"		=> $id,
							"skuid"		=> $skuid,
							"name"		=> $name,
							"price"		=> $price,
							"colour"	=> $colour,
							"size"		=> $size,
							"quantity"	=> $quantity,
							"colour_ids"=> $colour_ids,
							"size_ids"	=> $size_ids,
							'gift_wrapping' => $gift_wrapping,
							'gwPrice'	=> $gwPrice
						);		
					}
					
					// Discount the stock of the product.
					$this->setDB();
					
					//$strSQL = "Update product_catalog SET stock=stock-" . $quantity . " WHERE id=" . $id;
					/*$id_colour = "";
					$strSQL = "SELECT id FROM catalog_colour WHERE catalog_colour.title='" . $colour . "'";
					$result = @mysql_query($strSQL);
					if ($row = @mysql_fetch_assoc($result))
					{
						$id_colour = $row['id'];
					}
					
					$strSQL = "Update tl_catalog_attribute SET catalog_stock=catalog_stock-" . $quantity . " WHERE id_catalog=" . $id . " AND id_color=" . $id_colour . " AND id_size=" . $size;
					$result = @mysql_query($strSQL);*/
					
					if (!isset($_SESSION['CARTQUANTITY']) || !$_SESSION['CARTQUANTITY'])
						$_SESSION['CARTQUANTITY'] = 0;
					
					$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) + $quantity;
				}
			}
			
			// url generate.
			$strUri = $_SERVER['REQUEST_URI'];
			if (strpos($strUri, '#product_detail') !== false)
			{
				$strUrl = substr($strUri, 0, strpos($_SERVER['HTTP_HOST'], '#product_detail'));
			}
			else
			{
				$strUrl = $strUri;
			}
			
			if (strpos($strUrl, '?') !== false)
				if ($is_addItems)
					$strUrl .= "&add_tocart=success&stock=".$stock;
				else
					$strUrl .= "&add_tocart=failure&stock=".$stock;
			else
				if ($is_addItems)
					$strUrl .= "?add_tocart=success";
				else
					$strUrl .= "?add_tocart=failure&stock=".$stock;
			
			$strUrl = $_SERVER['HTTP_HOST'] . $strUrl;
		
		}
		else
		{
			$strUri = $_SERVER['REQUEST_URI'];
			if (strpos($strUri, '#product_detail') !== false)
			{
				$strUrl = substr($strUri, 0, strpos($_SERVER['HTTP_HOST'], '#product_detail'));
			}
			else
			{
				$strUrl = $strUri;
			}
			
			if (strpos($strUrl, '?') !== false)
				$strUrl .= "&add_tocart=failure&stock=0";
			else
				$strUrl .= "?add_tocart=failure&stock=0";
			
			$strUrl = $_SERVER['HTTP_HOST'] . $strUrl;
			
		}
		
		if ($url == '')
		{
			header("location:http://" . $strUrl);exit;
		}
		else
		{
			header("location:http://" . $_SERVER['HTTP_HOST'] . (($GLOBALS['TL_CONFIG']['websitePath']) ? ($GLOBALS['TL_CONFIG']['websitePath']) : '') . '/' . $url);exit;
		}		
	}
	
	public function updateCart()
	{
		$id				= $_POST['id'];
		$old_sessionID	= $_POST['session_id'];
		$colour		= $_POST['colour'];
		$size		= $_POST['size'];	
		$quantity	= $_POST['quantity'];
		
		$stock = 0;
		// Get the stock information of this special product.
		$strSQL = "SELECT `tl_catalog_attribute`.*, catalog_colour.title  
					FROM `tl_catalog_attribute` 
					LEFT JOIN `catalog_colour` ON `catalog_colour`.id=`tl_catalog_attribute`.id_color
					WHERE `tl_catalog_attribute`.`id_catalog`=" . $id . " AND `catalog_colour`.`title`='" . $colour . "'  AND `tl_catalog_attribute`.`id_size`=" . $size;
		$this->setDB();
		$result = @mysql_query($strSQL);
		if ($row=@mysql_fetch_assoc($result))
		{
			$stock = intval($row['catalog_stock']);
		}
		
		if(!$stock)
		{
			// None stock.
			header("location:shoppingcart.html?updated=failure&stock=0");exit;
		}
		elseif ($stock < intval($quantity))
		{
			header("location:shoppingcart.html?updated=failure&stock=$stock");exit;
		}
		else 
		{
			$sessionID	= $id."_".$size."_".trim(strtolower($colour));
			
			if($sessionID == $old_sessionID){
				if (intval($quantity) > intval($_SESSION['cart'][$sessionID]['quantity']))
				{
					// Change the stock.				
					/*$strSQL = "UPDATE `product_catalog` SET `stock`=`stock`-" . (intval($quantity) - intval($_SESSION['cart'][$sessionID]['quantity']));
					$result = @mysql_query($strSQL);*/
				}
				else
				{
					/*if (intval($quantity) < intval($_SESSION['cart'][$sessionID]['quantity']))
					{
						// Change the stock.
						$this->setDB();
						
						$strSQL = "UPDATE `product_catalog` SET `stock`=`stock`+" . (intval($_SESSION['cart'][$sessionID]['quantity']) - intval($quantity));
						$result = @mysql_query($strSQL);
					}*/
				}
				$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) + intval($quantity) - intval($_SESSION['cart'][$sessionID]['quantity']);
				$_SESSION['cart'][$sessionID]['quantity'] = $quantity;
			}else{
				if(isset($_SESSION['cart'][$sessionID])){
					$_SESSION['cart'][$sessionID]['gift_wrapping'] = ($_SESSION['cart'][$old_sessionID]['gift_wrapping']) ? $_SESSION['cart'][$old_sessionID]['gift_wrapping'] : $_SESSION['cart'][$sessionID]['gift_wrapping'];
					$_SESSION['cart'][$sessionID]['price'] = (intval($_SESSION['cart'][$old_sessionID]['price']) >= intval($_SESSION['cart'][$sessionID]['price'])) ? $_SESSION['cart'][$old_sessionID]['price'] : $_SESSION['cart'][$sessionID]['price'];
					$_SESSION['cart'][$sessionID]['quantity'] += $_SESSION['cart'][$old_sessionID]['quantity'];
					$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) + intval($quantity) - intval($_SESSION['cart'][$old_sessionID]['quantity']);
				}else{
					$_SESSION['cart'][$sessionID] = $_SESSION['cart'][$old_sessionID];
					$_SESSION['cart'][$sessionID]['colour'] = $colour;
					$_SESSION['cart'][$sessionID]['size'] = $size;
					$_SESSION['cart'][$sessionID]['quantity'] = $quantity;
					$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) + intval($quantity) - intval($_SESSION['cart'][$old_sessionID]['quantity']);
				}
				unset($_SESSION['cart'][$old_sessionID]);		
			}
			
			$_SESSION['cart']['sessionID'] = $sessionID;
			
			header("location:shoppingcart.html?updated=success");exit;
		}
	}	
	
	public function removeFromCart()
	{
		$sessionID = $_GET['sessionID'];
		
		// stock add one.
		$this->setDB();
		
		$quantity = $_SESSION['cart'][$sessionID]['quantity'];
		unset($_SESSION['cart'][$sessionID]);		
		/*$strSQL = "UPDATE `product_catalog` SET `stock`=`stock`+" . $_SESSION['cart']['quantity'];
		$result = @mysql_query($strSQL);*/
		
		$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) - $quantity;
		
		header("location:shoppingcart.html");exit;
	}
	
	public function removeToBackpocket()
	{
		$sessionID = $_GET['sessionID'];
		$this->setDB();
		
		if (isset($_COOKIE['FE_USER_AUTH']) && $_COOKIE['FE_USER_AUTH'])
		{
			$strSQL = "SELECT * FROM tl_session WHERE hash='" . $_COOKIE['FE_USER_AUTH'] . "' AND name='FE_USER_AUTH'";
			$result = @mysql_query($strSQL);
			
			$id_member = "";
			$backpocketCnt = 0;
			if ($arrResult = @mysql_fetch_assoc($result))
			{
				$id_member = $arrResult['pid'];
			}
			
			$strSQL = "SELECT COUNT(id_backpocket) AS cnt FROM `tl_backpocket` WHERE `id_member`=" . $id_member . " AND `id_catalog`=" . $_SESSION['cart'][$sessionID]['id'] . " AND `size`='" . $_SESSION['cart'][$sessionID]['size'] . "' AND `color`='" . $_SESSION['cart'][$sessionID]['colour'] . "'";
			$result = @mysql_query($strSQL);
			
			if ($arrResult = @mysql_fetch_assoc($result))
			{
				$backpocketCnt = intval($arrResult['cnt']);
			} 
			
			if (!$backpocketCnt)
			{
				$strSQL = "INSERT INTO `tl_backpocket` (`id_member`, `id_catalog`, `tstamp`, `size`, `color`, `quantity`, `is_wrapping`) VALUES ($id_member, " . $_SESSION['cart'][$sessionID]['id'] . ", " . time() . ", '" . $_SESSION['cart'][$sessionID]['size'] . "', '" . $_SESSION['cart'][$sessionID]['colour'] . "', '" . $_SESSION['cart'][$sessionID]['quantity'] . "'," . ($_SESSION['cart'][$sessionID]['gift_wrapping'] ? 1 : 0) . ")";
				$result = @mysql_query($strSQL);
			}
			else
			{
				$strSQL = "UPDATE `tl_backpocket` SET `tstamp`=" . time() . ", `size`='" . $_SESSION['cart'][$sessionID]['size'] . "', `color`='" . $_SESSION['cart'][$sessionID]['colour'] . "', `quantity`='" . $_SESSION['cart'][$sessionID]['quantity'] . "' WHERE `id_catalog`=" . $_SESSION['cart'][$sessionID]['id'] . " AND `id_member`=" . $id_member . " AND `size`='" . $_SESSION['cart'][$sessionID]['size'] . "' AND `color`='" . $_SESSION['cart'][$sessionID]['colour'] . "'";
				$result = @mysql_query($strSQL);
			}
			
			// Change the stock
			/*$strSQL = "UPDATE `product_catalog` SET `stock`=`stock`+" . $_SESSION['cart'][$sessionID]['quantity'] . " WHERE `id`=" . $_SESSION['cart'][$sessionID]['id'];
			$result = @mysql_query($strSQL);*/
		}
		else
		{
			$strRedirect = 'sign-in.html';
			//$strRedirect .= '?referer=' . base64_encode($_SERVER['REQUEST_URI']);
			$strRedirect .= '?referer=' . base64_encode('shoppingcart.html');
			
			/*$quantity = $_SESSION['cart'][$sessionID]['quantity'];
			unset($_SESSION['cart'][$sessionID]);		
			
			$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) - intval($quantity);*/
			
			header("location:$strRedirect");exit;
		}
		//$result = @mysql_query($strSQL);
		
		$quantity = $_SESSION['cart'][$sessionID]['quantity'];
		unset($_SESSION['cart'][$sessionID]);		
		
		$_SESSION['CARTQUANTITY'] = intval($_SESSION['CARTQUANTITY']) - intval($quantity);
		
		header("location:shoppingcart.html?action=movewishlist");exit;
	}

	private function setDB()
	{
		$strHost = $GLOBALS['TL_CONFIG']['dbHost'];
		if($GLOBALS['TL_CONFIG']['dbPort']){
			$strHost .= ':' . $GLOBALS['TL_CONFIG']['dbPort'];
		}

		if($GLOBALS['TL_CONFIG']['dbPconnect']){
			$resConnection = @mysql_pconnect($strHost, $GLOBALS['TL_CONFIG']['dbUser'], $GLOBALS['TL_CONFIG']['dbPass']);
		}else{
			$resConnection = @mysql_connect($strHost, $GLOBALS['TL_CONFIG']['dbUser'], $GLOBALS['TL_CONFIG']['dbPass']);
		}

		if (is_resource($resConnection)){
			@mysql_query("SET sql_mode=''", $resConnection);
			@mysql_query("SET NAMES " . $GLOBALS['TL_CONFIG']['dbCharset'], $resConnection);
			@mysql_select_db($GLOBALS['TL_CONFIG']['dbDatabase'], $resConnection);
		}
	}
	
}
?>